package danny.hoi.web.shiro;

import danny.hoi.domain.export.system.User;
import danny.hoi.domain.export.system.UserExample;
import danny.hoi.service.export.system.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class AuthRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取当前登陆账号和密码
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String email = (String) token.getPrincipal();
        //通过邮箱查找账号
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andEmailEqualTo(email);
        List<User> userList = userService.findAll(example);

        SimpleAuthenticationInfo sai = null;
        if (userList != null && userList.size() > 0) {
            User dbUser = userList.get(0);
            sai = new SimpleAuthenticationInfo(dbUser,
                    dbUser.getPassword(),
                    this.getName());
        }
        return sai;
    }
}

